package com.qyxx.platform.sysmng.notice.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qyxx.platform.common.utils.spring.SpringContextHolder;
import com.qyxx.platform.dwr.reverseajax.Comet;
import com.qyxx.platform.gsmng.common.service.ProcessTraceManager;
import com.qyxx.platform.sysmng.notice.entity.NoticeToUser;

public class NoticeTranspond implements Runnable {
	
	private static Logger logger = LoggerFactory.getLogger(NoticeTranspond.class);
	
	private NoticeManager noticeManager = SpringContextHolder.getBean("noticeManager");
	private ProcessTraceManager processTraceManager = SpringContextHolder.getBean("processTraceManager");
	
	@Override
	public void run() {
		Map<Long, Integer> userIdofNotice;
		Map<String, Integer> userIdofProcessTrace;
		try {
			userIdofNotice = getAllNoReadNotice();
			userIdofProcessTrace = getAllNoReadProcessTrace();
			Comet.push(userIdofNotice, userIdofProcessTrace);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("通知推送异常", e);
		}
	}
	
	//获取所有未读消息
	public Map<Long, Integer> getAllNoReadNotice() {
		Map<Long, Integer> userToNoticeNum = new HashMap<Long, Integer>();
		List<Object> counts = noticeManager.findNoReadNoticeCount();
		for(Object m : counts) {
			Map<String, Object> mm = (Map<String, Object>)m;
			Long userId = (Long)mm.get("userId");
			Integer count = Integer.parseInt(mm.get("count").toString());
			userToNoticeNum.put(userId, count);
		}
		return userToNoticeNum;
	}
	
	//获取所有待办事项
	public Map<String, Integer> getAllNoReadProcessTrace() {
		Map<String, Integer> userToProcessTraceNum = new HashMap<String, Integer>();
		List<Map<String, Object>> processTraceToUsers = processTraceManager.findAllUserTasksNum();
		if(processTraceToUsers != null && !processTraceToUsers.isEmpty()) {
			for(Map<String, Object> processTraceToUser : processTraceToUsers) {
				String username = (String)processTraceToUser.get("username");
				if(username!=null) {
					if(userToProcessTraceNum.containsKey(username)) {
						int count = userToProcessTraceNum.get(username) + 1;
						userToProcessTraceNum.put(username, count);
					} else {
						userToProcessTraceNum.put(username, 1);
					}
				}
			}
		}
		return userToProcessTraceNum;
	}
	
}
